package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理器
@Slf4j
@RestControllerAdvice   //作用：用来捕获所有的controller抛出的异常
// @ControllerAdvice
// @ResponseBody
public class GlobalHandlerException {

    @ExceptionHandler(Exception.class)  //用来指定要处理的异常类
    public Result doException(Exception ex){
        ex.printStackTrace();
        // log.error("异常信息：{}",ex.getMessage());
        return Result.error("出错啦！！！");
    }


    @ExceptionHandler(DuplicateKeyException.class)  //用来指定要处理的异常类
    public Result doSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("异常信息：{}",message);
        if (message.contains("Duplicate")) {
            // Duplicate entry '学工部' for key 'dept.name'
            String s = message.split(" ")[2]; //得到'学工部'
            return Result.error(s + "已存在！！！");
        }
        return Result.error("出错啦，请联系管理员！！！");
    }


}
